package com.zhangyj.component.tags;

import java.io.IOException;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

import com.zhangyj.LocalMessage;
import com.zhangyj.util.Pagination;

public class PaginationTag extends TagSupport {
	private static final long serialVersionUID = -3847144467200659625L;
	private String name;

	public int doEndTag() throws JspException {
		try {
			Pagination p = (Pagination) this.getValue(this.getName());
			if (p == null) {
				p = (Pagination) this.pageContext.getRequest().getAttribute(this.getName());
			}
			JspWriter out = this.pageContext.getOut();
			out.append("<table><tr><td>");
			out.append(LocalMessage.get("pagnation.current"));
			out.append("(" + p.getPage() + "/" + p.getTotalPage() + ")");
			out.append("</td><td>");
			String url = builderUrl(p.getUrl());
			if (p.hasPrePage()) {
				// 第一页
				writerPage(out, 1, url, "pagnation.first");
				out.append("&nbsp;|&nbsp;");
				// 上一页
				writerPage(out, p.getPrePage(), url, "pagnation.pre");
				if (p.hasNextPage()) {
					out.append("&nbsp;|&nbsp;");
				}
			}
			if (p.hasNextPage()) {
				// 下一页
				writerPage(out, p.getNextPage(), url, "pagnation.next");
				out.append("&nbsp;|&nbsp;");
				// 最后一页
				writerPage(out, p.getTotalPage(), url, "pagnation.last");
			}
			out.append("</td><td>");
			out.append(LocalMessage.get("pagnation.no"));
			out.append("</td><td>");
			out.append("<input class=\"pagnation\" size=\"2\" id=\"pagnation_").append(this.getName()).append("\"/>");
			out.append("</td><td>");
			out.append("</td><td>");
			out.append("<button class=\"pagnation\" type=\"button\" onclick=\"pagnation_go('");
			out.append(url);
			out.append("','pagnation_").append(this.getName()).append("',");
			out.append("" + p.getTotalPage() + ")\">GO</button>");
			out.append("</td>");
			out.append("</tr></table>");
		} catch (Exception e) {
			throw new JspException(e);
		}
		return EVAL_PAGE;
	}

	public String getName() {
		if (name == null) {
			return Pagination.ATTRIBUTE_ID;
		}
		return name;

	}

	public void setName(String name) {
		this.name = name;
	}

	private void writerPage(JspWriter out, int page, String url, String key) throws IOException {
		out.append("<a class=\"pagnation\" href=\"").append(url).append(page + "\">");
		out.append(LocalMessage.get(key)).append("</a>");
	}

	private String builderUrl(String url) throws IOException {
		StringBuilder builder = new StringBuilder();
		builder.append(this.pageContext.getServletContext().getContextPath());
		builder.append(url);
		if (url.indexOf('?') > -1) {
			builder.append("&");
		} else {
			builder.append('?');
		}
		builder.append(Pagination.PAGE_NAME);
		builder.append("=");
		return builder.toString();
	}
}
